package com.log.blog_backend.service.impls;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.log.blog_backend.common.Result;
import com.log.blog_backend.entity.User;
import com.log.blog_backend.entity.UserInfo;
import com.log.blog_backend.mapper.UserInfoMapper;
import com.log.blog_backend.mapper.UserMapper;
import com.log.blog_backend.service.UserService;
import com.log.blog_backend.utils.SnowFlake;
import com.log.blog_backend.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Resource
    private UserMapper userMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Autowired
    TokenUtil tokenUtil;
    @Override
    public Result noPwdLogin(String phone) {
        if(StringUtils.isNotBlank(phone)){
           //判断手机号是否注册过
              //是-> 就直接登录成功
            QueryWrapper<User>queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
            User user = userMapper.selectOne(queryWrapper);
            if(user!=null){
                //获取id
                String userId = user.getUserId();
                //获取常用的值存到浏览器中
                String account = user.getAccount();
                String avatar = user.getAvatar();
                //将id 添加到token里
                String token = tokenUtil.getToken(userId, "user");
                Map<String,String>map=new HashMap<>();
                map.put("nickname",account);
                map.put("avatar",avatar);
                map.put("token",token);
                return Result.ok(map);
            } else{
                //否-> 注册
                   //为了方便加userid添加到token 自行生产userid
                User newUser=new User();
                UserInfo userInfo=new UserInfo();
                String userid= new SnowFlake(1, 1, 1).StringIdMaker();
                   //创建token
                String token = tokenUtil.getToken(userid, "user");
                   //设置id
                newUser.setUserId(userid);
                userInfo.setUserId(userid);
                   //设置随机nickname
                String substring = userid.substring(0, 8);
                newUser.setAccount("user_"+substring);
                userInfo.setNickname("user_"+substring);

                    //统一头像
                newUser.setAvatar("https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png");

                Map<String,String>newMap=new HashMap<>();
                newMap.put("nickname", newUser.getAccount());
                newMap.put("avatar",newUser.getAvatar());
                newMap.put("token",token);
                //插入数据库
                userMapper.insert(newUser);
                userInfoMapper.insert(userInfo);
                //返回带有token的响应给前端
                return Result.ok(newMap);
            }

        }else {
            return Result.fail("手机号不能为空",600);
        }

    }

    @Override
    public String uploadAvatar(MultipartFile file, HttpServletRequest httpServletRequest) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tPZ77G575aWGG2e2cb6";
        String accessKeySecret = "2mv4HFqhyc61fzORZB3N4tYxsrc0F0";
        // 填写Bucket名称。
        String bucketName ="blog-avatar";
        //获取UserId
        String userId = tokenUtil.getUserIdByToken(httpServletRequest);

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();


            String objectName ="Avatar_"+userId;
            //看看是否存过头像
            boolean found = ossClient.doesObjectExist(bucketName, objectName);
            //存过就删除之前的头像
            if(found){
                ossClient.deleteObject(bucketName, objectName);
            }
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
            ossClient.shutdown();

            String url="https://"+bucketName+"."+endpoint+"/"+objectName;

            //存入数据库

            User user = userMapper.selectById(userId);
            user.setAvatar(url);
            int i = userMapper.updateById(user);
            System.out.println(">>>>>>>>>>>>>>>>>"+i);


            return url;

        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }

    @Override
    public Result changePassword(String newPassword, HttpServletRequest httpServletRequest) {
        String userId = tokenUtil.getUserIdByToken(httpServletRequest);
        User user = userMapper.selectById(userId);
       user.setPassword(newPassword);
        int i = userMapper.updateById(user);
        if (i>0){
            return Result.ok();
        }else {
            return  Result.fail("修改密码失败",4000);
        }

    }
}
